<template>
  <el-dialog
    :title="!dataForm.id ? 'add' : 'update'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="imageUrl" prop="imageUrl">
        <el-upload
          class="avatar-uploader"
          :headers="headers"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-remove="handleRemove">
          <img v-if="dataForm.imageUrl" :src="dataForm.imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="userName" prop="userName">
        <el-input v-model="dataForm.userName" placeholder="userName"></el-input>
      </el-form-item>
      <el-form-item label="realName" prop="realName">
        <el-input v-model="dataForm.realName" placeholder="realName"></el-input>
      </el-form-item>
      <el-form-item label="gender">
        <el-select v-model="dataForm.gender" placeholder="gender">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="password" prop="password" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" placeholder="password"></el-input>
      </el-form-item>
      <el-form-item label="comfirmPassword" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="comfirmPassword"></el-input>
      </el-form-item>
      <el-form-item label="email" prop="email">
        <el-input v-model="dataForm.email" placeholder="email"></el-input>
      </el-form-item>
      <el-form-item label="mobile" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="mobile"></el-input>
      </el-form-item>
      <el-form-item label="role" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="status" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">disable</el-radio>
          <el-radio :label="1">normal</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">cancel</el-button>
      <el-button type="primary" @click="dataFormSubmit()">sure</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import Vue from 'vue'
  import { isEmail, isMobile } from '@/utils/validate'
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('Password cannot be empty'))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('Confirm password cannot be empty'))
        } else if (this.dataForm.password !== value) {
          callback(new Error('The confirmed password is inconsistent with the password input'))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('Email format error'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('Mobile number format error'))
        } else {
          callback()
        }
      }
      return {
        uploadUrl: window.SITE_CONFIG['baseUrl'] + '/sys/user/uploadPicture',
        headers: { token: Vue.cookie.get('token') },
        visible: false,
        roleList: [],
        dataForm: {
          id: 0,
          userName: '',
          realName: '',
          gender: '',
          password: '',
          comfirmPassword: '',
          salt: '',
          email: '',
          mobile: '',
          imageUrl: '',
          roleIdList: [],
          status: 1
        },
        dataRule: {
          userName: [
            { required: true, message: 'User name cannot be empty', trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          comfirmPassword: [
            { validator: validateComfirmPassword, trigger: 'blur' }
          ],
          email: [
            { required: true, message: 'The mailbox cannot be empty', trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: 'Mobile number cannot be empty', trigger: 'blur' },
            { validator: validateMobile, trigger: 'blur' }
          ]
        },
        options: [
          {
            value: 0,
            label: 'man'
          },
          {
            value: 1,
            label: 'woman'
          },
          {
            value: 2,
            label: 'secrecy'
          }
        ]
      }
    },
    methods: {
      init (id) {
        console.log(id)
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/role/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.roleList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.userName = data.user.username
                this.dataForm.realName = data.user.realName
                this.dataForm.gender = data.user.gender
                this.dataForm.salt = data.user.salt
                this.dataForm.email = data.user.email
                this.dataForm.mobile = data.user.mobile
                this.dataForm.roleIdList = data.user.roleIdList
                this.dataForm.status = data.user.status
                this.dataForm.imageUrl = data.user.imageUrl
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'username': this.dataForm.userName,
                'realName': this.dataForm.realName,
                'gender': this.dataForm.gender,
                'password': this.dataForm.password,
                'salt': this.dataForm.salt,
                'email': this.dataForm.email,
                'mobile': this.dataForm.mobile,
                'status': this.dataForm.status,
                'imageUrl': this.dataForm.imageUrl,
                'roleIdList': this.dataForm.roleIdList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: 'Operation succeeded',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      handleAvatarSuccess (res, file) {
        this.dataForm.imageUrl = res.data.fileAddress
      },
      handleRemove (file, fileList) {
        console.log(file, fileList)
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('Uploading avatar images can only be in JPG format!')
        }
        if (!isLt2M) {
          this.$message.error('The size of the uploaded avatar image cannot exceed 2MB!')
        }
        return isJPG && isLt2M
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
